package com.zf.shuashua.api;

import android.Manifest;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.provider.Settings;
import android.text.TextUtils;

import androidx.core.app.ActivityCompat;

import com.meis.base.mei.utils.AppUtils;
import com.snail.antifake.deviceid.deviceid.DeviceIdUtil;
import com.zf.shuashua.ShuaApplication;
import com.zf.shuashua.advert.AdvertConstants;
import com.zf.shuashua.advert.CommitUtils;
import com.zf.shuashua.utils.EncryptUtils;
import com.zf.shuashua.utils.Util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;

import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class MyHttpInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        String method = request.method();

        Request.Builder requestBuilder = request.newBuilder();

        try {
            //TreeMap默认是升序
            TreeMap<String, String> map = new TreeMap();
            if ("GET".equals(method)) {
                HttpUrl httpUrl = request.url();
                Set<String> parameterNames = httpUrl.queryParameterNames();
                for (String key : parameterNames) {
                    String value = httpUrl.queryParameter(key);
                    if (value != null) {
                        map.put(key, value);
                    }
                }
            } else if ("POST".equals(request.method())) {
                // FormBody和url不太一样，若需添加公共参数，需要新建一个构造器
                FormBody.Builder bodyBuilder = new FormBody.Builder();
                // 把已有的post参数添加到新的构造器
                if (request.body() instanceof FormBody) {
                    FormBody formBody = (FormBody) request.body();
                    for (int i = 0; i < formBody.size(); i++) {
                        bodyBuilder.addEncoded(formBody.encodedName(i), formBody.encodedValue(i));
                    }
                    FormBody newBody = bodyBuilder.build();

                    for (int i = 0; i < newBody.size(); i++) {
                        map.put(newBody.name(i), newBody.value(i));
                    }
                }
            }
            String original = getOriginal(request.url());
            obtainHeaders(requestBuilder, original, method, map);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return chain.proceed(requestBuilder.build());
    }

    private String getOriginal(HttpUrl url) {
        String original = url.toString();
        int index = original.indexOf("?");
        if (index != -1) {
            original = original.substring(0, index);
        }
        return original;
    }

    /**
     * @param method GET 或者  POST
     * @param params 根据键值做字典顺序升序后用&连接成String，将String放在{}里
     * @return
     */
    private void obtainHeaders(Request.Builder builder, String url, String method, TreeMap<String, String> params) {
        String salt = getRandomString(10);
        String time = System.currentTimeMillis() + "";
        String terminal = "Android";
        String signatureVersion = "2.0";
        String key = AdvertConstants.getSignKey();
        String body = getBody(params);
        String sn = Util.getDeviceId(ShuaApplication.getContext());

        String str = "url=" + url + "&method=" + method + "&body=" + body + "&key=" + key + "&salt=" + salt
                + "&signature-version=" + signatureVersion + "&sn=" + sn + "&terminal=" + terminal + "&time=" + time;

        builder.addHeader("Authorization", ShuaApplication.token);
        builder.addHeader("salt", salt);
        builder.addHeader("time", time);
        builder.addHeader("sign", getSign(str, key, salt, time));
        builder.addHeader("sn", sn);
        builder.addHeader("channel", ShuaApplication.channel);
        builder.addHeader("api-version", CommitUtils.API_VERSION);
        builder.addHeader("signature-version", signatureVersion);
        builder.addHeader("terminal", terminal);
        if (!ShuaApplication.hasFirstStart) {
            builder.addHeader("isFirstLaunch", "1");
            ShuaApplication.hasFirstStart = true;
            Store.getInstance().setFirstStart(true);
            addDeviceInfo(builder);
        }else{
            if(!TextUtils.isEmpty(url)){
                if(url.contains("oauth/sms") || url.contains("oauth/oneclick") || url.contains("ogin/thirdLogin")){
                    addDeviceInfo(builder);
                }
            }
        }
    }

    private void addDeviceInfo(Request.Builder builder){
        if (TextUtils.isEmpty(ShuaApplication.imei)) {
            if (ActivityCompat.checkSelfPermission(ShuaApplication.context, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
                try {
                    ShuaApplication.imei = DeviceIdUtil.getDeviceId(ShuaApplication.context);
                    builder.addHeader("IMEI", ShuaApplication.imei);
                } catch (Exception e) {
                }
            }
        } else {
            builder.addHeader("IMEI", ShuaApplication.imei);
        }
        if(TextUtils.isEmpty(ShuaApplication.androidId)){
            ShuaApplication.androidId = AppUtils.getAndroidID(ShuaApplication.context);
        }
        builder.addHeader("ANDROIDID", ShuaApplication.androidId);
        builder.addHeader("OAID", ShuaApplication.oaid);
    }

    private String getSign(String str, String key, String salt, String time) {
        String hash = AdvertConstants.getCombinStr(key, salt, time);
        return EncryptUtils.encryptHmacSHA256ToString(str, hash).toLowerCase();
    }

    private String getBody(TreeMap<String, String> params) {
        if (params == null || params.isEmpty()) {
            return "{}";
        }
        StringBuilder builder = new StringBuilder();
        builder.append("{");

        String lastKey = params.lastKey();
        for (String key : params.keySet()) {
            builder.append(key);
            builder.append("=");
            builder.append(params.get(key));
            if (!lastKey.equals(key)) {
                builder.append("&");
            }
        }
        builder.append("}");

        return builder.toString();
    }

    private String getRandomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    private String ReadCNAdidN(Context ctx) {
        String adid = getCNAdID1(ctx);
        if (adid != null) {
            return adid;
        }
        adid = getCNAdID2(ctx);
        if (adid != null) {
            return adid;
        }
        adid = getCNAdID3(ctx);
        if (adid != null) {
            return adid;
        }
        return null;
    }

    private String getCNAdID2(Context ctx) {
        String result = null;
        String pkgName = ctx.getPackageName();
        SharedPreferences sp = ctx.getSharedPreferences(pkgName + "_dna", 0);
        result = sp.getString("ZHVzY2Lk", "NA");
        if (result.equals("NA")) {
            return null;
        }
        return result;
    }


    private String getCNAdID3(Context ctx) {
        String result = null;
        String path = "/sdcard/Android/ZHVzY2Lk";
        try {
            File file = new File(path);
            if (file.isDirectory() || !file.isFile()) {
                return null;
            }
            InputStream instream = new FileInputStream(file);
            InputStreamReader inputreader = new InputStreamReader(instream);
            BufferedReader buffreader = new BufferedReader(inputreader);
            String line = buffreader.readLine();
            if (line != null) {
                result = line;
            }
            instream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private String getCNAdID1(Context ctx) {
        String result = null;
        result = Settings.System.getString(ctx.getContentResolver(), "ZHVzY2Lk");
        return result;
    }

}
